package com.swt.gap.service.impl;

import com.swt.gap.common.constant.CommonConstant;
import com.swt.gap.common.FileTypeEnum;
import com.swt.gap.dao.FileDao;
import com.swt.gap.model.vo.UploadFileVO;
import com.swt.gap.service.UploadService;
import com.swt.gap.util.CsvReader;
import com.swt.gap.util.TimeFormatUtil;
import com.swt.gap.util.UserLoginUtils;
import com.swt.gap.util.excel.ExcelReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;

/**
 * @Author tyh
 * @Date 2020/4/22 16:17
 */

@Service
public class UploadServiceImpl implements UploadService {

    @Autowired
    private FileDao fileDao;

    @Override
    public UploadFileVO uploadFile(MultipartFile multipartFile, int fileClassId) throws IOException {
        UploadFileVO uploadFileVO = new UploadFileVO();
        Integer userId = UserLoginUtils.getUser().getUserId();

        String dir = CommonConstant.UPLOAD_DIR;
        File dirFile = new File(dir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        String originalFileName = multipartFile.getOriginalFilename();
        if (multipartFile != null) {
            if (!multipartFile.isEmpty()) {
                try {
                    //不带后缀的文件名
                    String fileName = originalFileName.substring(0, originalFileName.lastIndexOf("."));
                    //文件名超过20个字符则截取前20个字符
                    fileName = fileName.trim();
                    if (fileName.length() > 50) {
                        fileName = fileName.substring(0, 50);
                    }

                    String saveFileName = TimeFormatUtil.getCurrentTimeString() + "_" + originalFileName;
                    String filePath = dir + saveFileName;
                    String extension = originalFileName.substring(originalFileName.lastIndexOf("."));
                    fileName = fileName + extension;
                    //判断格式是否符合
                    for (FileTypeEnum typeEnum : FileTypeEnum.values()) {
                        if (typeEnum != FileTypeEnum.OTHER && filePath.endsWith(typeEnum.getSuffix())) {
                            //上传数据
                            File dest = new File(filePath);
                            multipartFile.transferTo(dest);

                            //判断csv和Excel文件有没有内容
                            if (FileTypeEnum.CSV.getSuffix().equals(extension)) {
                                CsvReader csvReader = new CsvReader(filePath);
                                List<String> header = csvReader.getHeader();
                                if (CollectionUtils.isEmpty(header)) {
                                    if (dest.exists()) {
                                        dest.delete();
                                    }
                                    //上传的文件是空文件
                                    UploadFileVO.FailedFile failedFile = new UploadFileVO.FailedFile();
                                    failedFile.setFailedFileName(originalFileName);
                                    failedFile.setErrorMessage("文件为空文件");
                                    failedFile.setErrorCode(5);
                                    uploadFileVO.setUploadSuccess(false);
                                    uploadFileVO.setFailedFile(failedFile);
                                    return uploadFileVO;
                                }
                            } else if (FileTypeEnum.EXCEL07.getSuffix().equals(extension) || FileTypeEnum.EXCEL03.getSuffix().equals(extension)) {
                                ExcelReader excelReader = new ExcelReader();
                                List<String> header = excelReader.read(filePath).getHeader();
                                if (CollectionUtils.isEmpty(header)) {
                                    if (dest.exists()) {
                                        dest.delete();
                                    }
                                    //上传的文件是空文件
                                    UploadFileVO.FailedFile failedFile = new UploadFileVO.FailedFile();
                                    failedFile.setFailedFileName(originalFileName);
                                    failedFile.setErrorMessage("文件为空文件");
                                    failedFile.setErrorCode(5);
                                    uploadFileVO.setUploadSuccess(false);
                                    uploadFileVO.setFailedFile(failedFile);
                                    return uploadFileVO;
                                }
                            }

                            //上传成功保存信息
                            UploadFileVO.FileInfo fileInfo = new UploadFileVO.FileInfo();
                            fileInfo.setOriginalFileName(fileName);
                            fileInfo.setSavedFileName(saveFileName);
                            fileInfo.setFileType(FileTypeEnum.getDataTypeCode(extension));
                            fileInfo.setFileClassId(fileClassId);
                            //获取文件大小
                            long size = multipartFile.getSize();
                            DecimalFormat format = new DecimalFormat("0.00");
                            String str = String.valueOf(size);
                            Double dd = Double.parseDouble(str) / 1024;
                            String sizess = format.format(dd);
                            fileInfo.setFileSize(Math.ceil(Double.parseDouble(sizess)));

                            //判断该用户是否上传了重名数据
                            List<com.swt.gap.model.entity.File> record = fileDao.selectSameFile(fileName,
                                    fileInfo.getFileType(), fileClassId, userId);
                            //有重名数据
                            if (record != null && !record.isEmpty()) {
                                //记录重名旧数据id
                                uploadFileVO.setOldFileId(record.get(0).getFileId());
                                //将数据信息新增到数据库
//                                Integer fileId = fileService.addNewFile(fileInfo, fileClassId, true);
//                                uploadFileVO.setFileId(fileId);

                                UploadFileVO.FailedFile failedFile = new UploadFileVO.FailedFile();
                                failedFile.setFailedFileName(originalFileName);
                                failedFile.setErrorMessage("该数据源名称已存在");
                                failedFile.setErrorCode(4);
                                failedFile.setSavedFileName(saveFileName);
                                failedFile.setFileSize(Math.ceil(Double.parseDouble(sizess)));
                                uploadFileVO.setUploadSuccess(false);
                                uploadFileVO.setFailedFile(failedFile);
                            } else {
                                //将数据信息新增到数据库
//                                Integer fileId = fileService.addNewFile(fileInfo, fileClassId, false);
//                                uploadFileVO.setFileId(fileId);
                                uploadFileVO.setSuccessFile(fileInfo);
                                uploadFileVO.setUploadSuccess(true);
                            }
                            return uploadFileVO;
                        }
                    }
                    //不符合格式记录信息
                    UploadFileVO.FailedFile failedFile = new UploadFileVO.FailedFile();
                    failedFile.setFailedFileName(originalFileName);
                    failedFile.setErrorMessage("数据格式不支持");
                    failedFile.setErrorCode(1);
                    uploadFileVO.setUploadSuccess(false);
                    uploadFileVO.setFailedFile(failedFile);
                    return uploadFileVO;

                } catch (Exception e) {
                    e.printStackTrace();
                    //上传失败记录信息
                    UploadFileVO.FailedFile failedFile = new UploadFileVO.FailedFile();
                    failedFile.setFailedFileName(originalFileName);
                    failedFile.setErrorMessage("系统问题，请联系管理员");
                    failedFile.setErrorCode(3);
                    uploadFileVO.setUploadSuccess(false);
                    uploadFileVO.setFailedFile(failedFile);
                    return uploadFileVO;
                }
            } else {
                //上传的文件是空文件
                UploadFileVO.FailedFile failedFile = new UploadFileVO.FailedFile();
                failedFile.setFailedFileName(originalFileName);
                failedFile.setErrorMessage("文件大小0kb,为空文件");
                failedFile.setErrorCode(5);
                uploadFileVO.setUploadSuccess(false);
                uploadFileVO.setFailedFile(failedFile);
                return uploadFileVO;
            }
        } else {
            //上传的文件不存在记录信息
            UploadFileVO.FailedFile failedFile = new UploadFileVO.FailedFile();
            failedFile.setFailedFileName(originalFileName);
            failedFile.setErrorMessage("原始文件不存在");
            failedFile.setErrorCode(2);
            uploadFileVO.setUploadSuccess(false);
            uploadFileVO.setFailedFile(failedFile);
            return uploadFileVO;
        }
    }

}
